<template>
    <div class="container">
        <!-- 左侧模块 -->
        <div class="left-section">
            <el-row>
                <el-col :span="12">
                    <el-row>
                        <el-col :span="8">
                            <el-input placeholder="输入查询信息" v-model="queryInfo"></el-input>
                        </el-col>
                        <el-col :span="2">
                            <el-button type="primary" @click="searchPatients">查询</el-button>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <el-table v-loading="loading" :data="tableData" border style="width: 100%"
                header-cell-class-name="table_header" @row-click="handleTableRowClick" stripe>
                <el-table-column label="档案号" prop="hisPatientId"></el-table-column>
                <el-table-column label="姓名" prop="patientName"></el-table-column>
                <el-table-column label="性别" prop="gender"></el-table-column>
                <el-table-column label="身份证" prop="idCard"></el-table-column>
                <el-table-column label="出生日期" prop="birthDay" :formatter="formatDate"></el-table-column>
                <el-table-column label="手机号" prop="phoneNum"></el-table-column>
                <el-table-column label="住址" prop="addr"></el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-pagination :current-page="currentPage" :page-size="pageSize" :total="total"
                layout="total,sizes,prev, pager, next,jumper" @current-change="handleCurrentChange"
                @size-change="handleSizeChange"></el-pagination>
        </div>
        <!-- 右侧模块 -->
        <div class="right-section">
            <!-- 患者信息表单 -->
            <el-card class="patient-info-card" v-loading="loadingright">
                <div slot="header" class="card-header">患者信息</div>
                <el-form :model="patientInfoForm">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="姓名">
                                <span>{{ patientInfoForm.patientName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="年龄">
                                <span>{{ patientInfoForm.age }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="性别">
                                <span>{{ patientInfoForm.gender }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="出生日期">
                                <span>{{ patientInfoForm.birthDay | formatDate}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="9">
                            <el-form-item label="身份证号">
                                <span>{{ patientInfoForm.idCard }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="联系电话">
                                <span>{{ patientInfoForm.phoneNum }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通讯地址">
                                <span>{{ patientInfoForm.addr }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="患者ID">
                                <span>{{ patientInfoForm.patientId }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="HIS患者ID">
                                <span>{{ patientInfoForm.hisPatientId }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="患者状态">
                                <span>{{ patientInfoForm.patientStates }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="就诊类别">
                                <span>{{ patientInfoForm.patientType }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="入院时间">
                                <span>{{ patientInfoForm.inHospitalTime| formatDate }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="医保费别">
                                <span>{{ patientInfoForm.insuranceType }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="就诊科室名称">
                                <span>{{ patientInfoForm.departmentName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="科室代码">
                                <span>{{ patientInfoForm.departmentCode }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="主治医生">
                                <span>{{ patientInfoForm.doctor }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="病床号">
                                <span>{{ patientInfoForm.bedNum }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="病区">
                                <span>{{ patientInfoForm.sickRegion }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="住院号">
                                <span>{{ patientInfoForm.admissionNum }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="主诉">
                                <span>{{ patientInfoForm.chiefComplaint }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="主要诊断">
                                <span>{{ patientInfoForm.coreDiagnosis }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <!-- 治疗医嘱与评估医嘱 -->
            <el-card class="order-card" style="overflow: hidden;" v-loading="loading">
                <div slot="header" class="card-header">评估医嘱</div>
                <el-table :data="adviceTableData" border style="width: 100%" header-cell-class-name="table_header">
                    <el-table-column label="批次 id" prop="batchId"></el-table-column>
                    <el-table-column label="医嘱 id" prop="hisAdviceId"></el-table-column>
                    <el-table-column label="患者 id" prop="patientId"></el-table-column>
                    <el-table-column label="患者系统 id" prop="hisPatientId"></el-table-column>
                    <el-table-column label="患者类别" prop="patientType"></el-table-column>
                    <el-table-column label="治疗项目 id" prop="treatmentId"></el-table-column>
                    <el-table-column label="医保类别" prop="insuranceType"></el-table-column>
                    <el-table-column label="执行疗程" prop="exePeriod"></el-table-column>
                    <el-table-column label="疗程次数" prop="periodNum"></el-table-column>
                    <el-table-column label="执行间隔" prop="exeInterval"></el-table-column>
                    <el-table-column label="执行间隔单位" prop="dicExeInterval"></el-table-column>
                    <el-table-column label="单次数量" prop="singleNum"></el-table-column>
                    <el-table-column label="治疗时间" prop="adviceTime"></el-table-column>
                    <el-table-column label="医嘱状态" prop="adviceStates"></el-table-column>
                    <el-table-column label="医嘱复核状态" prop="checkStates"></el-table-column>
                    <el-table-column label="申请医生" prop="applyDoctor"></el-table-column>
                    <el-table-column label="申请时间" prop="applyTime"></el-table-column>
                    <el-table-column label="申请科室编码" prop="applyDepartmentCode"></el-table-column>
                    <el-table-column label="复核医生" prop="checkDoctor"></el-table-column>
                    <el-table-column label="复核时间" prop="checkTime"></el-table-column>
                    <el-table-column label="执行医生" prop="exeDoctor"></el-table-column>
                    <el-table-column label="执行时间" prop="exeTime"></el-table-column>
                    <el-table-column label="执行科室编码" prop="exeDepartmentCode"></el-table-column>
                    <el-table-column label="执行次数" prop="exeNum"></el-table-column>
                    <el-table-column label="签署医生" prop="signDoctor"></el-table-column>
                    <el-table-column label="中断治疗原因" prop="treatmentInterruptionReason"></el-table-column>
                </el-table>
                <!-- 添加分页组件 -->
                <el-pagination :current-page="adviceCurrentPage" :page-size="advicePageSize" :total="adviceTotal"
                    layout="total,sizes,prev, pager, next,jumper" @current-change="handleAdviceCurrentChange"
                    @size-change="handleAdviceSizeChange"></el-pagination>
            </el-card>
            <!-- 执行记录 -->
            <!-- <el-card class="execution-record-card">
                <div slot="header" class="card-header">执行记录</div>
                <el-table :data="executionRecordData" border style="width: 100%">
                    <el-table-column label="" prop=""></el-table-column>
                </el-table>
            </el-card> -->
        </div>
    </div>
</template>

<script>
import { getDischargedPatients, queryPatientTreatmentInfo, queryPatientTreatmentAdviceInfo } from "@/api/patients/leaveinfo/info.js";
export default {
    name: "Leaveinfo",
    data() {
        return {
            // 左侧模块数据
            queryInfo: "",
            tableData: [],
            // 右侧模块数据
            //病人详细信息
            patientInfoForm: {},
            // 医嘱信息数据
            adviceTableData: [],
            // 分页相关属性
            currentPage: 1, // 当前页码，默认第1页
            pageSize: 10, // 每页显示的记录数，默认10条
            total: 0,// 总记录数，用于分页组件计算总页数
            // 评估医嘱分页相关属性
            adviceCurrentPage: 1, // 当前页码，默认第1页
            advicePageSize: 10, // 每页显示的记录数，默认10条
            adviceTotal: 0, // 总记录数，用于分页组件计算总页数
            riginalAdviceData: [], // 存储原始的完整医嘱数据
            loading: false,
            loadingright: false
        };
    },
    mounted() {
        // 首次渲染表格，调用查询患者信息接口并传入默认页码和每页记录数
        this.firstDrow().then(() => {
            if (this.tableData.length > 0) {
                // 如果表格数据存在，获取第一行数据并执行点击逻辑
                const firstRow = this.tableData[0];
                this.handleTableRowClick(firstRow);
            }
        });
    },
    methods: {
        // 首次渲染
        async firstDrow() {
            this.loading = true; // 设置为加载状态
            try {
                let res = await getDischargedPatients({
                    page: this.currentPage,
                    size: this.pageSize
                });
                // 更新总记录数，用于分页组件计算总页数
                if (res && res.code === 0 && res.content) {
                    this.total = res.totalElements;
                }
                this.processPatientData(res);
            } catch (error) {
                this.$notify({
                    title: '提示',
                    message: '网络出错了，请稍后再试!!!',
                    type: 'danger'
                });
            } finally {
                setTimeout(() => {
                    this.loading = false;
                }, 300)
            }
        },
        // 处理获取到的数据并填充到tableData数组
        processPatientData(data) {
            if (data && data.code === 0 && data.content) {
                this.tableData = data.content.map((patient) => ({
                    ...patient,
                    gender: patient.gender === 1 ? "男" : "女"
                }));
            }
        },

        // 查询 button，查询病人信息
        async searchPatients() {
            this.loading = true;
            const queryParams = {
                hisPatientId: '',
                patientName: this.queryInfo, // 使用queryInfo作为患者姓名进行筛选查询
                phoneNum: '',
                idCard: '',
                bedNum: '',
                outpatientNum: '',
                admissionNum: '',
                doctor: '',
                patientType: '',
                patientStates: '',
                page: this.currentPage,
                size: this.pageSize
            };
            try {
                let res = await getDischargedPatients(queryParams);
                // 更新总记录数
                if (res && res.code === 0 && res.content) {
                    this.total = res.totalElements;
                }
                this.processPatientData(res);
                // 拿到数据后toast查询成功
                if (res.totalElements === 0) {
                    this.$notify({
                        title: '提示',
                        message: '未查询到结果',
                        type: 'warning'
                    });
                } else {
                    this.$notify({
                        title: '提示',
                        message: '查询成功',
                        type: 'success'
                    });
                }
            } catch (error) {
                this.$notify({
                    title: '提示',
                    message: '网络出错了，请稍后再试',
                    type: 'danger'
                });
            } finally {
                setTimeout(() => {
                    this.loading = false;
                }, 300)
            }
        },

        // 处理每页显示条数变化的逻辑
        async handleSizeChange(value) {
            this.pageSize = value;
            let res = await getDischargedPatients({
                page: this.currentPage,
                size: this.pageSize
            })
            this.processPatientData(res);
        },

        // 页码变化
        async handleCurrentChange(newPage) {
            this.currentPage = newPage;
            let res = await getDischargedPatients({
                page: this.currentPage,
                size: this.pageSize
            })
            this.processPatientData(res)
        },

        //点击表格行数触发的回调
        async handleTableRowClick(row) {
            this.loadingright = true;
            const id = row.patientId;
            this.queryAdviceInfo(id);
            try {
                let res = await queryPatientTreatmentInfo({ id });
                if (res && res.code === 0 && res.content) {
                    this.patientInfoForm = {
                        ...res.content,
                        gender: res.content.gender === 1 ? "男" : "女",
                        patientStates: res.content.patientStates === 1 ? "在院" : "出院",
                        patientType: res.content.patientType === 1 ? "门诊" : (res.content.patientType === 2 ?
                            "住院" : "其他"),
                        insuranceType: res.content.insuranceType === 0 ? "自费" : "医保"
                    };
                    console.log(this.patientInfoForm,"this.patientInfoForm");
                    
                }
            } catch (error) {
                this.$notify({
                    title: '提示',
                    message: '获取患者详细信息网络出错了，请稍后再试',
                    type: 'danger'
                });
                console.log(error);
            } finally {
                setTimeout(() => {
                    this.loadingright = false;
                }, 300)
            }
        },

        //获取医嘱的回调
        async queryAdviceInfo(id) {
            try {
                let res = await queryPatientTreatmentAdviceInfo({ id });
                if (res && res.code === 0 && res.content) {
                    const convertData = res.content.map(item => {
                        return {
                            batchId: item.batchId,
                            hisAdviceId: item.id,
                            patientId: item.patientId,
                            hisPatientId: item.hisPatientId,
                            patientType: item.patientType === 1 ? "门诊" : (item.patientType === 2 ? "住院" : "其他"),
                            treatmentId: item.treatmentId,
                            insuranceType: item.insuranceType === 0 ? "自费" : "医保",
                            exePeriod: item.exePeriod,
                            periodNum: item.periodNum,
                            exeInterval: item.exeInterval,
                            dicExeInterval: item.dicExeInterval === 1 ? "天" : "",
                            singleNum: item.singleNum,
                            adviceTime: item.adviceTime,
                            adviceStates: this.getAdviceStatesText(item.adviceStates),
                            checkStates: item.checkStates === 0 ? "未复核" : "已复核",
                            applyDoctor: item.applyDoctor,
                            applyTime: item.applyTime,
                            applyDepartmentCode: item.applyDepartmentCode,
                            checkDoctor: item.checkDoctor,
                            checkTime: item.checkTime,
                            exeDoctor: item.exeDoctor,
                            exeTime: item.exeTime,
                            exeDepartmentCode: item.exeDepartmentCode,
                            exeNum: item.exeNum,
                            signDoctor: item.signDoctor,
                            treatmentInterruptionReason: this.getInterruptionReasonText(item.treatmentInterruptionReason)
                        };
                    });
                    this.adviceTableData = convertData;
                    this.originalAdviceData = convertData;
                    // 直接从接口返回数据中获取总记录数
                    this.adviceTotal = res.totalElements;
                    this.adviceCurrentPage = 1;
                    this.advicePageSize = 10;
                    this.updateAdviceTableData()
                } else {
                    // 处理接口返回无有效内容的情况，比如清空现有数据、重置分页相关属性等
                    this.adviceTableData = [];
                    this.originalAdviceData = [];
                    this.adviceTotal = 0;
                    this.adviceCurrentPage = 1;
                    this.advicePageSize = 10;
                }
            } catch (error) {
                // this.$notify({
                //     title: '提示',
                //     message: '获取患者医嘱出错了，请稍后再试',
                //     type: 'danger'
                // });
                console.log(error);
                // 同样在出现异常时，也进行数据清空和分页属性重置操作
                this.adviceTableData = [];
                this.originalAdviceData = [];
                this.adviceTotal = 0;
                this.adviceCurrentPage = 1;
                this.advicePageSize = 10;
            }
        },

        //医嘱状态
        getAdviceStatesText(status) {
            const statusMap = {
                0: "未提交",
                1: "已提交",
                2: "已签署",
                3: "执行中",
                4: "已完成",
                5: "已作废"
            };
            return statusMap[status] || "";
        },
        //中断治疗原因
        getInterruptionReasonText(reason) {
            const reasonMap = {
                1: "治愈",
                2: "无效",
                3: "出院",
                4: "不适应",
                5: "其他"
            };
            return reasonMap[reason] || "";
        },

        // 处理评估医嘱每页显示条数变化的逻辑
        async handleAdviceSizeChange(value) {
            this.advicePageSize = value;
            this.updateAdviceTableData();
        },

        // 处理评估医嘱页码变化的逻辑
        async handleAdviceCurrentChange(newPage) {
            this.adviceCurrentPage = newPage;
            this.updateAdviceTableData();
        },

        // 根据当前页码和每页显示条数更新 adviceTableData 的方法
        updateAdviceTableData() {
            const start = (this.adviceCurrentPage - 1) * this.advicePageSize;
            const end = start + this.advicePageSize;
            this.adviceTableData = this.originalAdviceData.slice(start, end);
        },

        //格式化出生日期
        formatDate(row, column, cellValue, index) {
            if (cellValue) {
                const date = new Date(cellValue);
                const year = date.getFullYear();
                const month = ('0' + (date.getMonth() + 1)).slice(-2);
                const day = ('0' + date.getDate()).slice(-2);
                return `${year}年${month}月${day}日`;
            }
            return '';
        },
    },
    filters: {
        formatDate(value) {
            if (value) {
                const date = new Date(value);
                const year = date.getFullYear();
                const month = ('0' + (date.getMonth() + 1)).slice(-2);
                const day = ('0' + date.getDate()).slice(-2);
                return `${year}年${month}月${day}日`;
            }
            return '';
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.container {
    display: flex;
    justify-content: space-between;

    /deep/.table_header {
        // background-color: #eef1f6;
        text-align: center;
        // color: white;    
        background-color: rgb(238, 241, 246);
        color: rgb(96, 98, 102);
    }

    .left-section {
        width: 50%;
        padding: 10px;

        .el-row {
            margin-bottom: 5px;

            .el-form-item {
                margin: 0 15px;
            }
        }
    }

    .right-section {
        padding: 10px;
        width: 50%;

        span {
            padding: 5px;
            background-color: azure;
            min-width: 20px;
        }

        /deep/.el-card__header {
            padding: 10px 15px;
        }

        .el-tabs {
            margin-bottom: 0px;
        }

        /deep/.el-tabs__item {
            height: 30px;
            line-height: 30px;
        }

        .patient-info-card {
            margin-bottom: 10px;
        }

        .order-card {
            margin-bottom: 10px;
        }

        .execution-record-card {
            margin-bottom: 10px;
        }
    }
}
</style>